package com.sds.sweng.swat.miplatform.ui.design.policies;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.gef.requests.CreateRequest;

import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformComponent;
import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformContainer;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TableSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.commands.CopySubAreaCommand;
import com.sds.sweng.swat.miplatform.ui.design.models.commands.CopyTableCommand;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.sub.TableSubAreaPart;
import com.sds.sweng.swat.miplatform.ui.design.utils.EditPolicyUtils;

public class TableLayoutEditPolicy extends LayoutEditPolicy {

	protected Command getAddCommand(Request request) {
		ChangeBoundsRequest req = (ChangeBoundsRequest) request;
		List<EditPart> editParts = req.getEditParts();

		if (editParts == null || editParts.size() == 0)
			return null;

		if (!(editParts.get(0) instanceof TableSubAreaPart))
			return null;

		TableSubAreaPart host = (TableSubAreaPart) getHost();
		TableSubAreaPart guest = (TableSubAreaPart) editParts.get(0);

		TableSubArea hostModel = (TableSubArea) host.getModel();
		TableSubArea guestModel = (TableSubArea) guest.getModel();

		if (hostModel.getWidth() != guestModel.getWidth())
			return null;

		if (hostModel.getTable().getColumns().size() > 0 || guestModel.getTable().getTableCells().size() == 0)
			return null;

		CopyTableCommand command = new CopyTableCommand(hostModel, guestModel.getTable());

		return command;
	}

	protected EditPolicy createChildEditPolicy(EditPart child) {
		return new NonResizableEditPolicy();
	}

	@Override
	protected Command getCreateCommand(CreateRequest request) {
		return EditPolicyUtils.createCopySubAreaCommand(request, getHost());
	}

	@Override
	protected Command getMoveChildrenCommand(Request request) {
		return null;
	}

}
